package com.boot.config.datasource

import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.After
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Before
import org.aspectj.lang.reflect.MethodSignature
import org.springframework.stereotype.Component

import java.lang.reflect.Method

/**
 * @author kawins
 * createTime 2018-12-08 10:16
 */
@Aspect
@Component
class DynamicDataSourceAspect {

    @Before("@annotation(OracleDb)")
    fun beforeSwitchDB(point: JoinPoint) {
        val className = point.target.javaClass
        val methodName = point.signature.name
        val argClass = (point.signature as MethodSignature).parameterTypes
        try {
            val method = className.getMethod(methodName, *argClass)
            if (method.isAnnotationPresent(OracleDb::class.java)) {
                val annotation = method.getAnnotation(OracleDb::class.java)
                val dataName = annotation.value
                DatabaseContextHolder.databaseType = dataName
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @After("@annotation(OracleDb)")
    fun afterSwitchDB(point: JoinPoint) {
        DatabaseContextHolder.default()
    }
}